package com.cloudansys.core.util;

import com.cloudansys.config.DefaultConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class MqttUtil {

    /**
     * 向 mqtt 发布消息
     *
     * @param topic   发送的主题
     * @param message 发送的消息
     */
    public static void sendToMqtt(MqttClient mqttClient, String topic, String message) {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(1);
        mqttMessage.setRetained(false);
        mqttMessage.setPayload(message.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        try {
            mqttTopic.publish(mqttMessage);
        } catch (MqttException e) {
            log.error("Mqtt 消息发送失败！");
            e.printStackTrace();
        }
    }

    /**
     * 向 mqtt 发布消息
     *
     * @param topic   发送的主题
     * @param message 发送的消息
     */
    public static void sendToMqtt(String topic, String message) {
        MqttClient mqttClient = DefaultConfig.getMqttClient();
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(1);
        mqttMessage.setRetained(false);
        mqttMessage.setPayload(message.getBytes());
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        try {
            mqttTopic.publish(mqttMessage);
        } catch (MqttException e) {
            log.error("Mqtt 消息发送失败！");
            e.printStackTrace();
        }
        try {
            mqttClient.disconnect();
            mqttClient.close();
        } catch (MqttException e) {
            log.error("Mqtt 连接关闭失败！");
            e.printStackTrace();
        }
    }

}
